package cn.itcast.rnk.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStreamsDemo {

	static final String dataFile = "invoicedata";

	static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
	static final int[] units = { 12, 8, 13, 29, 50 };
	static final String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DataOutputStream outputStream = null;
		DataInputStream in = null;
		try {
			outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Dataoutfile.txt")));

			for (int i = 0; i < prices.length; i++) {
				outputStream.writeDouble(prices[i]);
				;
				outputStream.writeInt(units[i]);
				;
				outputStream.writeUTF(descs[i]);
				;
			}

			outputStream.flush();
			in = new DataInputStream(new BufferedInputStream(new FileInputStream("Dataoutfile.txt")));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		double price;
		int unit;
		String desc;
		double total = 0.0;

		while (true) {
			try {
				price = in.readDouble();
				unit = in.readInt();
				desc = in.readUTF();
				System.out.format("You ordered %d" + " units of %s at $%.2f%n", unit, desc, price);
				total += unit * price;

			} catch (EOFException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				if (outputStream != null) {
					try {
						outputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}

	}

}
